package service

import (
	"app/common"
	"app/global"
	"app/model"
	mongodbutil "app/pkg/db"
	"app/utils"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"log"
)

type UserService struct {
}

func (u UserService) Save(info model.UserInfo) {
	//collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.UserInfoCollection)
	//rr, err := collection.InsertOne(ctx, info)
	//if err != nil {
	//	fmt.Println(err)
	//	fmt.Println(rr)
	//}
	fmt.Println(123)

}

func (u UserService) Get(id string) model.UserInfo {
	collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.UserInfoCollection)
	filter := bson.D{{"id", id}}
	cur, err := collection.Find(ctx, filter)
	if err != nil {
		log.Fatal(err)
	}
	var results []model.UserInfo
	if err = cur.All(ctx, &results); err != nil {
		log.Fatal(err)
	}

	for _, result := range results {
		fmt.Println(result)
	}
	if len(results) == 0 {
		return model.UserInfo{}
	}
	return results[0]

}

func (u UserService) Delete(id string) {
	collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.UserInfoCollection)
	filter := bson.D{{"id", id}}
	_, err := collection.DeleteOne(ctx, filter)
	if err != nil {
		log.Fatal(err)
	}
}

func (u UserService) Login(loginName string, password string) string {
	collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.UserInfoCollection)
	filter := bson.D{{"loginname", loginName}, {"password", password}}
	cur, err := collection.Find(ctx, filter)
	if err != nil {
		log.Fatal(err)
	}
	var results []model.UserInfo
	if err = cur.All(ctx, &results); err != nil {
		log.Fatal(err)
	}
	UserClaims := utils.UserClaims{
		UserId:   results[0].ID,
		Username: results[0].LoginName,
	}

	jwt, _ := utils.GenerateToken(&UserClaims)
	return jwt
}
